package org.xlp.db.bridge.defination;

import org.xlp.db.bridge.annotation.Mapper;
import org.xlp.db.bridge.type.MapperEnum;
import org.xlp.utils.XLPPackingTypeUtil;

import java.io.Serializable;

/**
 * Description: 获取当前数据表操作类型，即：增/删/查/改
 * <br/>date: 2024/4/17 11:26
 *
 * @version 1.0
 * @author: xlp
 */
class DbCRUDTypeUtils {
    /**
     * 数据更新函数前缀
     */
    public static final String UPDATE_PREFIX = "update";

    /**
     * 数据保存函数前缀
     */
    public static final String SAVE_PREFIX = "save";

    /**
     * 数据删除函数前缀
     */
    public static final String DELETE_PREFIX = "delete";

    /**
     * 获取数据表操作类型
     * @param mapper
     * @param methodName
     * @param returnType
     * @return
     */
    public static MapperEnum getDbCRUDType(Mapper mapper, String methodName, Class<?> returnType){
        MapperEnum type = mapper.type();
        if (type != MapperEnum.AUTO) return type;

        //返回类型为void，则判定为数据改变
        if (returnType == null || returnType == Void.TYPE || returnType == Void.class) {
            if (methodName.startsWith(SAVE_PREFIX)){
                return MapperEnum.SAVE;
            }
            return MapperEnum.CHANGE;
        }

        if (XLPPackingTypeUtil.isNumberType(returnType)){
            if (methodName.startsWith(SAVE_PREFIX)){
                return MapperEnum.SAVE;
            }
            if (methodName.startsWith(UPDATE_PREFIX) || methodName.startsWith(DELETE_PREFIX)){
                return MapperEnum.CHANGE;
            }
        }

        Class<?> componentType = returnType.getComponentType();
        // 判断是否是保存数据操作
        if (returnType == Integer.class || returnType == String.class
            || componentType == Integer.class || componentType == String.class) {
            if (methodName.startsWith(SAVE_PREFIX)){
                return MapperEnum.SAVE;
            }
        }

        return MapperEnum.QUERY;
    }
}
